import { ApiResponse } from '../../types';

// 管理员权限检查中间件
export const adminMiddleware = async (ctx: any, next: any) => {
  if (!ctx.state.user || ctx.state.user.role !== 'admin') {
    ctx.status = 403;
    ctx.body = {
      success: false,
      message: "需要管理员权限"
    } as ApiResponse;
    return;
  }
  await next();
};

// 管理员权限检查函数（用于在路由内部检查）
export const checkAdminPermission = (ctx: any): boolean => {
  if (!ctx.state.user || ctx.state.user.role !== 'admin') {
    ctx.status = 403;
    ctx.body = {
      success: false,
      message: "需要管理员权限"
    } as ApiResponse;
    return false;
  }
  return true;
};

// 分页参数处理
export interface PaginationParams {
  page: number;
  limit: number;
  offset: number;
}

export const getPaginationParams = (ctx: any): PaginationParams => {
  const page = parseInt(ctx.query.page as string) || 1;
  const limit = Math.min(parseInt(ctx.query.limit as string) || 20, 100); // 最大100条
  const offset = (page - 1) * limit;
  
  return { page, limit, offset };
};

// 分页响应数据格式
export interface PaginatedResponse<T> {
  items: T[];
  pagination: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
}

export const createPaginatedResponse = <T>(
  items: T[], 
  total: number, 
  page: number, 
  limit: number
): PaginatedResponse<T> => {
  const totalPages = Math.ceil(total / limit);
  
  return {
    items,
    pagination: {
      page,
      limit,
      total,
      totalPages,
      hasNext: page < totalPages,
      hasPrev: page > 1
    }
  };
};

// 搜索参数处理
export interface SearchParams {
  keyword?: string;
  startDate?: string;
  endDate?: string;
  status?: string;
  [key: string]: any;
}

export const getSearchParams = (ctx: any): SearchParams => {
  const { keyword, startDate, endDate, status, ...others } = ctx.query;
  
  return {
    keyword: keyword as string,
    startDate: startDate as string,
    endDate: endDate as string,
    status: status as string,
    ...others
  };
};

// 通用错误处理
export const handleError = (ctx: any, error: any, message: string = "操作失败") => {
  console.error(`管理员操作错误:`, error);
  ctx.status = 500;
  ctx.body = {
    success: false,
    message,
    error: {
      type: "admin_error",
      message: error.message,
      timestamp: new Date().toISOString()
    }
  } as ApiResponse;
};

// 成功响应
export const successResponse = (ctx: any, data: any, message: string = "操作成功") => {
  ctx.body = {
    success: true,
    data,
    message,
    timestamp: new Date().toISOString()
  } as ApiResponse;
};

// 验证ID参数
export const validateId = (ctx: any, paramName: string = 'id'): number | null => {
  const id = parseInt(ctx.params[paramName]);
  if (isNaN(id) || id <= 0) {
    ctx.status = 400;
    ctx.body = {
      success: false,
      message: `无效的${paramName}参数`
    } as ApiResponse;
    return null;
  }
  return id;
};

// 批量操作验证
export const validateBatchIds = (ctx: any): number[] | null => {
  const { ids } = ctx.request.body as { ids: any };
  
  if (!Array.isArray(ids) || ids.length === 0) {
    ctx.status = 400;
    ctx.body = {
      success: false,
      message: "请提供有效的ID数组"
    } as ApiResponse;
    return null;
  }
  
  const validIds = ids.filter(id => Number.isInteger(id) && id > 0);
  if (validIds.length === 0) {
    ctx.status = 400;
    ctx.body = {
      success: false,
      message: "没有有效的ID"
    } as ApiResponse;
    return null;
  }
  
  return validIds;
}; 